package com.SpringRSSReader;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
//import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
//import android.content.Intent;
//import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class RssItemDisplayer extends Activity {
	
	private class DownloadTask extends AsyncTask<String, Void, Boolean> {

	    @Override
	    protected Boolean doInBackground(String... params) {
	    	String downUrl = params[0];
	        try {
	        	URL url = new URL(downUrl);
	    		//Intent downloadIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(downUrl));
	    		//startActivity(downloadIntent);
	    		
	    		int nDeli = downUrl.lastIndexOf('/');
	    		nDeli++;
	    		String subFileName = downUrl.substring(nDeli);
	    		String fileName = getFilesDir() + "/" + subFileName;
	    		Log.d("SPRING_TAG","URL:" + url + "\nfileName:" + fileName);
	    		File file = new File(fileName);
	    		long startTime = System.currentTimeMillis();		        
	    		Log.d("DownLoad", "download begining");
	    		Log.d("DownLoad", "download url:" + url);
	    		Log.d("DownLoad", "downloaded file name:" + fileName);
	    		// Open a connection to that URL.
	    		URLConnection ucon = url.openConnection();
	    		// Define InputStreams to read from the URLConnection.
	    		InputStream is = ucon.getInputStream();
	    		BufferedInputStream bis = new BufferedInputStream(is);
	    		// Read bytes to the Buffer until there is nothing more to read(-1).
	    		ByteArrayBuffer baf = new ByteArrayBuffer(50);
	    		int current = 0;
	    		while ((current = bis.read()) != -1) {
	    			baf.append((byte) current);
	    		}
	    		// Convert the Bytes read to a String.
	    		FileOutputStream fos = new FileOutputStream(file);
	    		fos.write(baf.toByteArray());
	    		fos.close();
	    		Log.d("DownLoad", "download ready in"
	    				+ ((System.currentTimeMillis() - startTime) / 1000)
	    				+ " sec");	        	
	        	/*
	            URL url = new URL(params[0]);
	            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
	            //Input stream from the connection
	            InputStream in = new BufferedInputStream(connection.getInputStream());
	            //Output stream to a file in your application's private space
	            FileOutputStream out = openFileOutput("filename", Activity.MODE_PRIVATE);

	            //Read and write the stream data here
	        	 */
	            return true;                
	        } catch (Exception e) {
	            e.printStackTrace();
	            return false;
	        }

	    }

	    @Override
	    protected void onPostExecute(Boolean result) {
	        //Post a notification once complete
	        NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
	        Notification note;
	        if(result) {
	            note = new Notification(0, "Download Complete", System.currentTimeMillis());
	        } else {
	            note = new Notification(0, "Download Failed", System.currentTimeMillis());
	        }
	        manager.notify(100, note);
	    }
	} // DownloadTask
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rss_item_displayer);
		Log.i("SPRING_TAG","RSS_item_displayer");
		final RssItem selectedRssItem = com.SpringRSSReader.ShowListActivity.selectedRssItem;
		//Bundle extras = getIntent().getExtras();
		TextView titleTv = (TextView)findViewById(R.id.titleTextView);	
		TextView contentTv = (TextView)findViewById(R.id.contentTextView);	

		Button downEpi = (Button)findViewById(R.id.downEpi);
		
		String title = "";
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd - hh:mm:ss");
		title = "\n Title: \n" + selectedRssItem.getTitle() + "\n   ( "
				+ sdf.format(selectedRssItem.getPubDate()) + " )\n\n";
		
		String content = "";
		content += "Desc:\n" + selectedRssItem.getDescription() + "\n"
				+ "Link: \n" + selectedRssItem.getLink();// + "\n\nDownload: \n" + selectedRssItem.getEnclosure();
		
		titleTv.setText(title);
		//contentTv.setText(content);
		contentTv.setText(Html.fromHtml(content));
		// define the action that will be executed when the button is clicked.
        downEpi.setOnClickListener(new OnClickListener() {
	        @Override
	        public void onClick(View v) {
	        	Log.d("SPRING_TAG","Click downEpi");
	        	// Code for download
	        	//String downUrl = selectedRssItem.getEnclosure();
	        	String downUrl = "http://www.archive.org/download/spring_podcast_title/podcast_title.jpg";
	        	new DownloadTask().execute(downUrl);
		        //downLoadFromUrl(downUrl);
		        //String downUrl = "http://www.archive.org/download/spring_podcast_title/podcast_title.jpg";
		        //int nPosExpand = downUrl.lastIndexOf('.');
		        //int nLenUrl = downUrl.length();
		        //String streamUrl = downUrl.substring(0,nPosExpand-1) + "_512kb" + downUrl.substring(nPosExpand, nLenUrl - 1);
		        
		        //Log.i(DEBUG_TAG,"URL: "  + feedUrl);
	        } // OnClick
        }); // setClickListener
	} // OnCreate
	
/*	
	private void downLoadFromUrl(String downUrl) {
		
		try {
    		URL url = new URL(downUrl);
    		//Intent downloadIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(downUrl));
    		//startActivity(downloadIntent);
    		
    		int nDeli = downUrl.lastIndexOf('/');
    		nDeli++;
    		String subFileName = downUrl.substring(nDeli);
    		String fileName = getFilesDir() + "/" + subFileName;
    		Log.d("SPRING_TAG","URL:" + url + "\nfileName:" + fileName);
    		File file = new File(fileName);
    		long startTime = System.currentTimeMillis();		        
    		Log.d("DownLoad", "download begining");
    		Log.d("DownLoad", "download url:" + url);
    		Log.d("DownLoad", "downloaded file name:" + fileName);
    		// Open a connection to that URL.
    		URLConnection ucon = url.openConnection();
    		// Define InputStreams to read from the URLConnection.
    		InputStream is = ucon.getInputStream();
    		BufferedInputStream bis = new BufferedInputStream(is);
    		// Read bytes to the Buffer until there is nothing more to read(-1).
    		ByteArrayBuffer baf = new ByteArrayBuffer(50);
    		int current = 0;
    		while ((current = bis.read()) != -1) {
    			baf.append((byte) current);
    		}
    		// Convert the Bytes read to a String.
    		FileOutputStream fos = new FileOutputStream(file);
    		fos.write(baf.toByteArray());
    		fos.close();
    		Log.d("DownLoad", "download ready in"
    				+ ((System.currentTimeMillis() - startTime) / 1000)
    				+ " sec");
    		
    	} catch (IOException e) {
    		Log.d("SPRING_TAG", "Error: " + e);
    	}
	} //downFromUrl
*/	
	
}
